<?php
class FT_Cat {
	private $info = array();
	private $posts = array();
	private $post = null;
	private $extras;
	
	/* CONSTRUCTOR */
	
	function FT_Cat($cat_id = null, $extras = true) {
		$this->info['id'] = $cat_id;
		$this->extras = $extras;
		
		$this->FT_Crear_Info();
		$this->FT_Crear_Posts();
	}
	
	/* METODOS PRIVADOS */
	
	/* Crea la info basica de la categoria */
	
	private function FT_Crear_Info() {
		global $wp_query;
		
		if(is_null($this->info['id'])) :
			$this->info = array(
				'id' => $wp_query->cat,
				'current' => true
			);
		else :
			$this->info['current'] = false;
			if($this->info['id'] == $wp_query->cat)
				$this->info['current'] = true;
		endif;
		
		$this->info['name'] = get_cat_name($this->info['id']);
	}
	
	/* Crea un listado con los post del blog (ciudad) */
	
	private function FT_Crear_Posts() {
		global $wpdb, $wp_query, $post;
		
		if($this->extras) :
			$sql = $wpdb->prepare("SELECT {$wpdb->posts}.ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND {$wpdb->posts}.ID IN (SELECT {$wpdb->term_relationships}.object_id FROM {$wpdb->term_relationships} WHERE {$wpdb->term_relationships}.term_taxonomy_id = {$this->info['id']}) ORDER BY post_date DESC;");
			$posts_id = $wpdb->get_col($sql);
			
			if(!empty($posts_id)) :
				if($wp_query->post_count == 1)
					$current_post_id = $wp_query->post->ID;
				elseif($wp_query->post_count == 0)
					$current_post_id = $post->ID;
				
				foreach($posts_id as $post_id) :
					$this->posts[$post_id] = new FT_Post($post_id);
					if(!isset($this->post) && $this->posts[$post_id]->FT_Get_Info('current') && $post_id == $current_post_id) :
						$this->post = $this->posts[$post_id];
						if(!$this->info['current'])
							$this->info['current'] = true;
					endif;
				endforeach;
				
				if(!isset($this->post)) :
					unset($this->post);
				endif;
			else :
				unset($this->posts);
				unset($this->post);
			endif;
		else :
			unset($this->posts);
			unset($this->post);
		endif;
	}
	
	/* METODOS PUBLICOS */
	
	/* Devuelve la info basica de la categoria */
	
	public function FT_Get_Info($info_name = '') {
		if(empty($info_name))
			return $this->info;
		else
			return $this->info[strtolower($info_name)];
	}
	
	/* Devuelve el o los posts de la categoria */
	
	public function FT_Get_Posts($post_id = null) {
		if(is_null($post_id))
			return $this->posts;
		else
			return $this->posts[$post_id];
	}
	
	/* Devuelve el post actual del blog (ciudad) */
	
	public function FT_Get_Current_Post() {
		return $this->post;
	}
}
?>